package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 得到官方接口
 *
 */
@Slf4j
public class Plugin_ECARD_P014 implements ChannelService {

    /*查余额*/
    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    /*提交订单*/
    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data){

        try {
            Map dataParams = new LinkedHashMap<String, Object>();
            /*
             * 合作方编码 partner_no
             * 签名串 - 签名获取 sign
             * 订单号 order_no
             * 产品SKU - 第三方提供 sku
             *  数量 amount -int
             *  金额 payment -int
             *  用户手机号 mobile
             * */
            String AccountVal = String.valueOf(data.get("AccountVal"));
            if (Pattern.matches("^1[3456789]\\d{9}$", AccountVal) != true) {
                return  ChannelResult.error("手机号码异常");
            }
            dataParams.put("partner_no",apiConfig.getString("partnerNumber"));
            dataParams.put("order_no",String.valueOf(data.get("ChannelOrderCode")));//订单号
            dataParams.put("amount",1); //数量

            BigDecimal money=new BigDecimal(String.valueOf(data.get("PurchasePrice"))).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_DOWN);
            dataParams.put("payment",money); //金额

            dataParams.put("mobile" ,AccountVal);//电话
            dataParams.put("sku",String.valueOf(data.get("SUPProductId")));
            dataParams.put("area_code","86");
            dataParams.put("version","1.0");

            String pubkey=apiConfig.getString("pubKey"); //测试环境 pubKey

            String url = apiConfig.getString("OrderUrl");

            //签名
            String signature = getSignature(dataParams, pubkey);

            dataParams.put("sign",signature);//签名

            String result = HttpTool.HttpPost2(url, dataParams);
            JSONObject objectRes = JSONObject.parseObject(result);
            String code = objectRes.getString("code");
            String msg = objectRes.getString("msg");

            if("00000".equals(code) && "成功".equals(msg)){
                //JSONObject orderNumber = objectRes.getJSONObject("data"); //成功返回订单号
                return  ChannelResult.success("充值成功");
            }
            if("00005".equals(code)){
                return  ChannelResult.IN_PROCESS("充值中");
            }
            else {
                return ChannelResult.FAILED(code+","+msg);
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("得到提交订单接口错误：",e);
            return  ChannelResult.error("得到提交订单接口错误");
            }
        }

    /*查询第三方接口订单*/
    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            Map queryParams = new LinkedHashMap<String, String>();
            /*
             * 合作方编码 partner_no
             * 签名串 - 签名获取 sign
             * 订单号 order_no
             * 产品SKU - 第三方提供 sku
             *  数量 amount -int
             *  金额 payment -int
             *  用户手机号 mobile
             * */
            queryParams.put("partner_no",apiConfig.getString("partnerNumber"));
            queryParams.put("order_no",String.valueOf(data.get("ChannelOrderCode")));
            String pubkey=apiConfig.getString("pubKey"); //测试环境 pubKey

            String signature = getSignature(queryParams, pubkey);

            String url = apiConfig.getString("QueryUrl");
            queryParams.put("sign",signature);
            String result = HttpTool.HttpPost(url, queryParams);

            JSONObject retobj = JSONObject.parseObject(result);
            String code = retobj.getString("code");
            String msg = retobj.getString("msg");
            if ("00000".equals(code) && "成功".equals(msg)) {
                JSONObject respData = retobj.getJSONObject("data");
                Integer status = respData.getInteger("status");
                if (status.equals(0)){
                    return  ChannelResult.IN_PROCESS("充值成功，但权益还未开通");
                }
                return  ChannelResult.success("充值成功，已开通权益");
            }else {
                return ChannelResult.FAILED(code+","+msg);
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("得到查询订单接口错误：",e);
            return  ChannelResult.error("得到查询订单接口错误");
        }

    }

    /*接收第三方回调*/
    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }


    /*对参数进行处理并排序*/
    public static String createLinkString(Map<String, Object> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key) == null ? "" : String.valueOf(params.get(key));

            if (null != value && !"".equals(value)) {
                if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                    prestr = prestr + key + "=" + value;
                } else {
                    prestr = prestr + key + "=" + value + "&";
                }
            }
        }
        log.info(prestr);
        return prestr;

    }

    public static String getSignature(Map dataParams, String pubkey){
       try {
           String linkString = createLinkString(dataParams);
           log.info(linkString);
           System.out.println(dataParams);
           Mac sha256Hmac = Mac.getInstance("HmacSHA256");
           SecretKeySpec secretKey = new SecretKeySpec(pubkey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
           sha256Hmac.init(secretKey);

           byte[] hmacResult = sha256Hmac.doFinal(linkString.getBytes(StandardCharsets.UTF_8));
           String sign = Base64.getEncoder().encodeToString(hmacResult);

           log.info(sign);
           //DuADJB5QRILS381fYzu92iU4tFiS46JcXTU5wm+x5Rw= 充值
           //DuADJB5QRILS381fYzu92iU4tFiS46JcXTU5wm+x5Rw= 查询
           return sign;
       }catch (Exception e) {
           log.info("获取签名失败");
           return null;
        }

    }

}
